import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import Footer from "../components/Footer";
import Header from "../components/Header";
import { userLogin } from "../service";

export default function Login() {
   // 状态变量--用户名
   let [uname,setUname]=useState("")
   // 状态变量--密码 
   let [upwd,setUpwd]=useState("")
  //  在最外层
   let nav = useNavigate()
   let doLogin=async()=>{
    // console.log(uname,upwd);
    // 将用户输入提交给服务器端接口,进行登录验证
    let data=await userLogin(uname,upwd)
    console.log(data);
    if(data.code===1){
      // 1.显示欢迎消息
      window.alert('欢迎回来'+uname)
      // 2，在客户端保存服务器返回的身份令牌
      localStorage['userToken']=data.token
      // 3.页面跳转“登录原因页”
      let url=localStorage['loginReason']
      delete localStorage['loginReason']  //即将跳转回登录原因页,客户端不需在保存了
      
      nav(url)
    }else{
      window.alert('登录失败:'+data.msg)
    }
   }
   
  return (
    <>
      {/* F1:页头 */}
      <Header></Header>
      {/* F2:主体 */}
      <div className="login_box">
        <div className="container">
          <div className="login">
            <h2>用户登录</h2>
            <dl className="clearfloat">
              <dt>
                <span className="tips" id="uname_prompt_text"></span>用户名：
              </dt>
              <dd>
                <input value={uname} onChange={e=>setUname(e.target.value)} type="text" id="uname" placeholder="邮箱/手机号" />
                <em className="icon_user"></em>
                <i className="icon_error" id="uname_prompt_icon"></i>
              </dd>
            </dl>
            <dl>
              <dt>
                <span className="tips" id="pwd_prompt_text">
                  请输入密码
                </span>
                密码：
              </dt>
              <dd>
                <input value={upwd} onChange={e=>setUpwd(e.target.value)} type="password" id="pwd" placeholder="密码" />
                <em className="icon_pwd"></em>
                <i className="icon_error" id="pwd_prompt_icon"></i>
              </dd>
            </dl>
            <p>
              <label>
                <input type="checkbox" />
                <span>自动登录</span>
              </label>
            </p>
            <button type="button" id="login" onClick={doLogin}>
              立 即 登 录
            </button>
          </div>
        </div>
      </div>
      {/* F3:页头 */}
      <Footer></Footer>
    </>
  );
}
